<?php

declare(strict_types=1);

namespace app\model\admin;

use app\model\AdminBaseModel;
use think\Model;

/**
 * @mixin \think\Model
 */
class Product extends AdminBaseModel
{
    // 数据表名称
    protected $table = 'product';
    protected $scopeField = true;

    //可搜索字段
    protected $searchField = [];
    // like
    protected $singleSearchField = ['name'];
    //可作为条件的字段
    protected $whereField = ['status'];
    //可做为时间范围查询的字段
    protected $timeField = ['created_at'];
    public function cate()
    {
        return $this->belongsTo(CateModel::class, 'cate_id', 'id');
    }
    // public function cates()
    // {
    //     return $this->hasMany(ProductCate::class, 'product_id', 'id');
    // }
    public function attrKey()
    {
        return $this->hasMany(ProductAttr::class, 'product_id', 'id');
    }
    public function attrValue()
    {
        return $this->hasMany(ProductAttrValue::class, 'product_id', 'id');
    }
    public function attrRes()
    {
        return $this->hasOne(ProductAttrResult::class, 'product_id', 'id');
    }
    public function setSliderImageAttr($value)
    {
        if ($value && is_array($value)) {
            $this->set('slider_image', json_encode($value));
        }
    }
    public function getSliderImageAttr($value, $data)
    {
        if (isset($data['slider_image'])) {
            return json_decode($data['slider_image'], true);
        }
    }
    public function getCustomFormAttr($value, $data)
    {
        if (isset($data['custom_form'])) {
            return json_decode($data['custom_form'], true);
        }
    }

    public function setCustomFormAttr($value)
    {
        if ($value && is_array($value)) {
            $this->set('custom_form', json_encode($value));
        }
    }
    public function setCateIdAttr($value)
    {
        if ($value && is_array($value)) {
            $this->set('cate_id', implode(',', $value));
        }
    }
    // public function getCateIdAttr($value, $data)
    // {
    //     if (isset($data['cate_id'])) {
    //         return explode(',', $data['cate_id']);
    //     }
    // }
    public function attr_value()
    {
        return $this->hasMany(ProductAttrValue::class, 'product_id', 'id');
    }
}
